package com.en.controller.Word;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.en.config.GlobalConfig;
import com.en.config.VoiceConfig;
import com.en.utils.TTS;
import com.microsoft.cognitiveservices.speech.AudioDataStream;
import com.microsoft.cognitiveservices.speech.SpeechSynthesisResult;
import com.microsoft.cognitiveservices.speech.audio.AudioConfig;
import com.microsoft.cognitiveservices.speech.audio.PullAudioOutputStream;
import io.swagger.annotations.*;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.en.response.AppException;
import com.en.response.ErrorCodeMsgEnum;
import com.en.model.Word;
import com.en.service.WordService;
import com.en.controller.Word.*;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.en.response.R;
import com.en.utils.Tools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;


/**
 * @Description:
 * @Author: wht
 * @Date: 2024-01-16
 */
@Slf4j
@RestController
@RequestMapping("/")
@Api(tags = {"操作"})
public class WordController {
    @Autowired
    WordService wordService;


    @ApiOperation("新增一个")
    @PutMapping("/addOneWord")
    public <T> R<T> addOneWord(@Valid @RequestBody WordAddDto addDto) {
        log.info(String.valueOf(addDto));
        //        生成语音（单词） ----------
        String word = addDto.getWord();
        if (addDto.getAudio_word() == null) {
            String audio_url = TTS.wordEnToSpeechUs(word);
            addDto.setAudio_word(audio_url);
        }

        //        生成语音（翻译） ----------
        String translate = addDto.getTranslate();
        String comment = addDto.getComment();
        if (comment != null) {
            translate += "。" + comment;
        }
        String audio_url = TTS.chineseToSpeech(translate);
        addDto.setAudio_translate(audio_url);

//        存数据库--------
        Word wordObj = new Word();
        BeanUtils.copyProperties(addDto, wordObj);
        boolean res = wordService.save(wordObj);

        if (res) {
            return R.successMsg("添加成功！");
        } else {
            throw new AppException(ErrorCodeMsgEnum.ADD_ERROR);
        }
    }

    @ApiOperation("删除一个")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", dataType = "Integer", required = true)}
    )
    @DeleteMapping("/deleteOneWord/{id}")
    public <T> R<T> deleteOneWord(@PathVariable("id") Integer id) {
        if (id == null) {
            throw new AppException(ErrorCodeMsgEnum.REQUEST_PARAMS_ERROR);
        }
        boolean res = wordService.removeById(id);

        if (res) {
            return R.successMsg("删除成功！");
        } else {
            throw new AppException(ErrorCodeMsgEnum.DELETE_ERROR);
        }
    }

    @ApiOperation("修改一个信息")
    @PatchMapping("/updateOneWord")
    public <T> R<T> updateOneWord(@Valid @RequestBody WordUpdateDto updateDto) {
        String word = updateDto.getWord();
        if (word != null && updateDto.getAudio_word() == null) {
            //        生成语音 ----------
            String audio_url = TTS.wordEnToSpeechUs(word);
            updateDto.setAudio_word(audio_url);
        }

        String translate = updateDto.getTranslate();
        String comment = updateDto.getComment();
        if (translate != null || comment != null) {
            String translateAll = "";
            if (translate != null && comment != null) {
                translateAll = translate + "。" + comment;
            } else {
                Word _word = wordService.getById(updateDto.getId());
                if (translate == null) {
                    translateAll = _word.getTranslate()  + "。" + comment;
                } else {
                    translateAll = translate  + "。" + _word.getComment();
                }
            }
            //        生成语音 ----------
            String audio_url = TTS.chineseToSpeech(translateAll);
            updateDto.setAudio_translate(audio_url);
        }

        Word wordObj = new Word();
        BeanUtils.copyProperties(updateDto, wordObj);
        boolean res = wordService.updateById(wordObj);

        if (res) {
            return R.successMsg("修改成功！");
        } else {
            throw new AppException(ErrorCodeMsgEnum.UPDATE_ERROR);
        }
    }

    @ApiOperation("通过id重置单词发音（微软）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", dataType = "Integer", required = true)}
    )
    @GetMapping("/resetWordSpeechWR/{id}")
    public <T> R<T> resetWordSpeechWR(@PathVariable("id") Integer id) {
        if (id == null) {
            throw new AppException(ErrorCodeMsgEnum.REQUEST_PARAMS_ERROR);
        }

        Word word = wordService.getById(id);
        String speech_url = TTS.wordEnToSpeechUs(word.getWord());


        Word word1 = new Word();
        word1.setId(word.getId());
        word1.setAudio_word(speech_url);
        boolean res = wordService.updateById(word1);

        if (res) {
            return R.successMsg("修改成功！");
        } else {
            throw new AppException(ErrorCodeMsgEnum.UPDATE_ERROR);
        }
    }

    @ApiOperation("重置所有单词和翻译的发音")
    @GetMapping("/resetAllWordSpeech")
    public <T> R<T> resetAllWordSpeech() {
        List<Word> list = wordService.list();
        log.info("开始重置，总共：" + list.size());
        int i = 0;
        for (Word word : list) {
            String speech_en_url = TTS.wordEnToSpeechUs(word.getWord());
//            翻译 -----------start
            String translate = word.getTranslate();
            String comment = word.getComment();
            if (comment != null && !"".equals(comment)) {
                translate += "。" + comment;
            }
            String speech_zh_url = TTS.chineseToSpeech(translate);
//            翻译 -----------start
            Word word_new = new Word();
            word_new.setId(word.getId());
            word_new.setAudio_word(speech_en_url);
            word_new.setAudio_translate(speech_zh_url);
            if (!wordService.updateById(word_new)) {
                throw new AppException(ErrorCodeMsgEnum.UPDATE_ERROR);
            }
            i++;
            log.info("重置完成：" + word.getWord() + "-------------" + i);
        }
        return R.successMsg("修改成功！");
    }


    @ApiOperation("通过id获取一个信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", dataType = "Integer", required = true)}
    )
    @GetMapping("/getOneWord/{id}")
    public <T> R<T> getOneWord(@PathVariable("id") Integer id) {
        if (id == null) {
            throw new AppException(ErrorCodeMsgEnum.REQUEST_PARAMS_ERROR);
        }
        Word word = wordService.getById(id);
        return R.successData(word);
    }

    @ApiOperation("分页获取列表")
    @PostMapping("/getWordList")
    public <T> R<T> getWordList(@Valid @RequestBody WordSearchDto searchDto) throws IllegalAccessException {
        QueryWrapper<Word> queryWrapper = new QueryWrapper<>();

        Field[] fields = searchDto.getClass().getDeclaredFields();
        for (Field field : fields) {
            String name = field.getName();
            if (name.equals("page_num") || name.equals("page_size")) continue;
            field.setAccessible(true); // 必须将字段设置为可访问
            Object value = field.get(searchDto);
            if (value != null) {
                queryWrapper.eq(name, value);
            }
        }

        Page<Word> page = new Page<>(searchDto.getPage_num(), searchDto.getPage_size());
        wordService.page(page, queryWrapper);

        HashMap<Object, Object> res = new HashMap<>();
        res.put("page_size", page.getSize());
        res.put("page_num", page.getCurrent());
        res.put("total", page.getTotal());
        res.put("list", page.getRecords());
        return R.successData(res);
    }

    @ApiOperation("获取所有列表")
    @GetMapping("/getAllWordList")
    public <T> R<T> getAllWordList() {
        List<Word> list = wordService.list();

        return R.successData(list);
    }
}
